package com.tingyuge.base.structrue.quene;

import java.util.Date;

public class MyArrayQueue<T> {
    private T[] data;
    private int top;
    private int bottom;

    public MyArrayQueue() {
        data = (T[]) new Object[10];
        top = 0;
        bottom = -1;
    }

    public T pop() {
        if (bottom - top == -1) {
            throw new IndexOutOfBoundsException("为空");
        }

        T result = data[top % data.length];
        top++;
        if (bottom - top + 1 == data.length / 4 && data.length / 2 != 0) {
            grow(data.length / 2);
        }
        return result;
    }

    public void push(T t) {
        bottom++;
        data[bottom % data.length] = t;
        if (bottom - top + 1 == data.length) {
            grow(data.length * 2);
        }
    }

    public T peek() {
        return data[top % data.length];
    }

    private void grow(int n) {

        int newLength = n;
        T[] newData = (T[]) new Object[newLength];
        if (top != 0) {
            System.arraycopy(data, top % data.length, newData, 0, data.length - top % data.length);
        }

        System.arraycopy(data, 0, newData, (data.length - top % data.length) % data.length, bottom % data.length + 1);

        top = 0;
        bottom = data.length - 1;
        data = newData;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("容量:" + data.length + "  ");
        for (int i = top; i < bottom + 1; i++) {
            builder.append(data[i] + "->");
        }
        return builder.toString();

    }

    public void clean() {
        data = (T[]) new Object[10];
        top = 0;
        bottom = 0;
    }

    public int size() {
        return bottom - top + 1;
    }

    public static void main(String[] args) {

        MyArrayQueue<Integer> queue = new MyArrayQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.push(i);
        }
        System.out.println(queue);
        queue.pop();
        queue.pop();
        queue.pop();
        queue.pop();
        queue.pop();
        queue.pop();
        queue.pop();
        queue.pop();



    }
}